package top.lshaci.learning.netty.rpc.comsumer;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * NettyClient
 *
 * @author lshaci
 * @since 1.0.0
 */
public class NettyClient {

    /**
     * 创建线程池
     */
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static NettyRpcClientHandler client;
    private int count;

    public Object getBean(final Class<?> serviceClass, final String providerName) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serviceClass}, (proxy, method, args) -> {
                    final Log log = LogFactory.get(this.getClass());
                    log.debug("代理方法进入 {} 次", ++count);
                    if (client == null) {
                        initClient();
                    }
                    System.err.println("===========");
                    // 设置要发给服务端的消息
                    // providerName 协议头  arg[0]  就是客户端调用 api hello(???) 的参数
                    client.setPara(providerName + args[0]);
                    System.err.println("消息：" + args[0]);
                    return executor.submit(client).get();
                });
    }

    private void initClient() {
        client = new NettyRpcClientHandler();
        // 客户端只需要一个事件循环组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(client);
                        }
                    });
            final ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 7000).sync();
            System.err.println("客户端启动完成。。");
            // 对关闭通道进行监听
//            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            group.shutdownGracefully();
        }
    }
}
